﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace LiveCodeServer
{
    public class User
    {
        #region Private Variables
        private int iID = -1;
        private string sName = "";

        /// <summary>
        /// List of project ids the user is in
        /// </summary>
        private List<int> lstProjects = new List<int>();

        /// <summary>
        /// Client class associated with this user
        /// </summary>
        private Client userClient;
        #endregion

        #region Public Properties
        public int ID
        {
            get
            {
                return this.iID;
            }
        }
        public string Name
        {
            get
            {
                return this.sName;
            }
        }
        public Client Client
        {
            get
            {
                return this.userClient;
            }
        }
        public List<int> ProjectIDs
        {
            get
            {
                return this.lstProjects;
            }
        }
        public Project ConnectedProject
        {
            get;
            set;
        }
        #endregion

        public User(XmlNode xmlUserNode, Client _userClient)
        {
            try
            {
                //Make sure that this is a valid user node with a single id and name
                if (xmlUserNode.SelectNodes("ID").Count == 1 && xmlUserNode.SelectNodes("Name").Count == 1)
                {
                    this.userClient = _userClient;

                    this.iID = int.Parse(xmlUserNode.SelectSingleNode("ID").InnerText);
                    this.sName = xmlUserNode.SelectSingleNode("Name").InnerText;

                    this.lstProjects.Clear();
                    XmlNodeList projectIDNodes = xmlUserNode.SelectNodes("Projects/ProjectID");
                    foreach (XmlNode projectID in projectIDNodes)
                    {
                        int iProjectID = int.Parse(projectID.InnerText);
                        this.lstProjects.Add(iProjectID);
                    }
                }
                else
                {
                    throw new XmlException("Invalid xml node for user");
                }
            }
            catch (Exception e)
            {
                //TODO handle better

                string message = "Method: User.User";
                message += "\nUser: " + this.ID.ToString();
                message += "\nException: " + e.Message;

                this.userClient.ClientHandler.AddMessage(message, System.Drawing.Color.Red);
            }
        }
    }
}
